package com.demo2do.fms.admin.web.controller.supplier.sub.flow;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.search.supplier.TractorSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.service.supplier.TractorService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.vehicle.AuditStatus;
import com.demo2do.fms.entity.vehicle.DeclareStatus;
import com.demo2do.fms.entity.vehicle.tractor.Tractor;
import com.demo2do.fms.entity.vehicle.tractor.TractorModifiedVersion;

/**
 * 分属供方牵引车审核
 *
 * @author Ark
 *
 */
@Controller
@RequestMapping("/tractor-audits")
@MenuSetting("menu-supplier")
public class TractorAuditController {
    
    private static final Logger logger = LoggerFactory.getLogger(TractorAuditController.class);
    
    @Autowired
    private TractorService tractorService;
    
    @Autowired
    private SupplierService supplierService;
    
    /**
     * 分属供方车辆审核列表
     * 
     * @param login
     * @param status
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET)
    @MenuSetting("submenu-editing-tractor-management")
    public ModelAndView list(@Secure Login login, @RequestParam(name = "declareStatus", required = false, defaultValue = "UNSYNC") DeclareStatus declareStatus,
                             HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/tractor/tractor-audit-list");
        modelAndView.addObject("declareStatus", declareStatus);
        
        int totals = tractorService.countAudit(login, declareStatus);
        if (totals > 0) {
            
            List<Tractor> tractors = tractorService.listAudit(login, declareStatus, page.with(totals));
            modelAndView.addObject("tractors", tractors);
            
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 过滤查询panel
     * 
     * @param status
     * @return
     */
    @RequestMapping(value = "/search" , method = RequestMethod.GET )
    public ModelAndView search(@RequestParam("declareStatus") DeclareStatus declareStatus){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/tractor/tractor-audit-search");
        
        modelAndView.addObject("declareStatus", declareStatus);
        
        return modelAndView;
        
    }
    
    /**
     * 过滤查询
     * 
     * @param login
     * @param search
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET  , params = "filter")
    @MenuSetting("submenu-editing-tractor-management")
    public ModelAndView onSearch(@Secure Login login, TractorSearch search,
                                 HttpServletRequest request, Page page){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/tractor/tractor-audit-list");
        modelAndView.addObject("declareStatus", search.getDeclareStatus());
        
        List<Long> supplierIds = supplierService.listSubSupplierId(login);
        search.addSupplierId(supplierIds);
        
        List<AuditStatus> statuses = Arrays.asList(AuditStatus.AUDITING, AuditStatus.MODIFIED);
        search.addStatus(statuses);
        
        int totals = tractorService.count(search);
        if (totals > 0) {
            
            List<Tractor> tractors = tractorService.search(search, page.with(totals));
            
            modelAndView.addObject("tractors", tractors);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 变更牵引车详情
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET, params = "declareStatus=MODIFIED")
    @MenuSetting("submenu-editing-tractor-management")
    public ModelAndView view(@PathVariable("id") Long id) {

        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/tractor/tractor-audit-view");
        
        Tractor tractor = tractorService.load(Tractor.class, id);
        modelAndView.addObject("tractor", tractor);
        
        TractorModifiedVersion version = tractorService.loadModifiedVersion(tractor);
        modelAndView.addObject("version", version);
        
        return modelAndView;
        
    }
    
    /**
     * 引入审核/变更审核 - 通过panel
     * 
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/{id}/adopt" , method = RequestMethod.GET)
    public ModelAndView adopt(@PathVariable("id") Long id, @RequestParam("declareStatus") DeclareStatus declareStatus){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/tractor/tractor-audit-adopt");
        
        modelAndView.addObject("id", id);
        modelAndView.addObject("declareStatus", declareStatus);
        
        return modelAndView;
        
    }

    /**
     * 引入审核 - 通过
     * 
     * @param operator
     * @return
     */
    @RequestMapping(value = "/{id}/adopt" , method = RequestMethod.PATCH , params = "declareStatus=UNSYNC", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onAdoptAuditing(@PathVariable("id") Long id, @Secure(property = "id") Long operator){
        
        HttpResult httpResult = new HttpResult();
        
        try {

            Tractor tractor = tractorService.load(Tractor.class, id);
            tractorService.adoptAuditing(tractor, operator);
            
            httpResult.success().message("审核通过成功");
            
        } catch (Exception e) {
            logger.error("onAuditingAdopt - adopt fail, exception = [{}]", e);
            httpResult.fail("500").message("审核通过失败");
        }
        
        return httpResult;
    }
    
    /**
     * 变更审核 - 通过
     * 
     * @param operator
     * @param vehicleSource
     * @return
     */
    @RequestMapping(value = "/{id}/adopt" , method = RequestMethod.PATCH , params = "declareStatus=MODIFIED", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onAdoptModified(@PathVariable("id") Long id, @Secure(property = "id") Long operator) {
        
        HttpResult httpResult = new HttpResult();
        
        try {

            Tractor tractor = tractorService.load(Tractor.class, id);
            tractorService.adoptModified(tractor, operator);
            
            httpResult.success().message("审核通过成功");
            
        } catch (Exception e) {
            logger.error("onModifiedAdopt - adopt fail, exception = [{}]", e);
            httpResult.fail("500").message("审核通过失败");
        }
        
        return httpResult;
    }
    
    /**
     * 引入审核/变更审核 - 驳回panel
     * 
     * @param id
     * @param status
     * @return
     */
    @RequestMapping(value = "/{id}/reject" , method = RequestMethod.GET)
    public ModelAndView reject(@PathVariable("id") Long id, @RequestParam("declareStatus") DeclareStatus declareStatus){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/tractor/tractor-audit-reject");
        
        modelAndView.addObject("id", id);
        modelAndView.addObject("declareStatus", declareStatus);
        
        return modelAndView;
        
    }

    /**
     * 引入审核 - 驳回
     * 
     * @param operator
     * @param vehicleSource
     * @return
     */
    @RequestMapping(value = "/{id}/reject" , method = RequestMethod.PATCH , params = "declareStatus=UNSYNC", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onRejectAuditing(@Preloading("id") Tractor tractor, @Secure(property = "id") Long operator){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            tractorService.rejectAudit(tractor, operator);
            
            httpResult.success().message("驳回成功");
            
        } catch (Exception e) {
            logger.error("onAuditingReject() - reject fail, exception = [{}]", e);
            httpResult.fail("500").message("驳回失败");
        }
        
        return httpResult;
        
    }
    
    /**
     * 变更审核 - 驳回
     * 
     * @param operator
     * @param vehicleSource
     * @return
     */
    @RequestMapping(value = "/{id}/reject" , method = RequestMethod.PATCH , params = "declareStatus=MODIFIED", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onRejectModified(@Preloading("id") Tractor tractor, @Secure(property = "id") Long operator){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            tractorService.rejectModified(tractor, operator);
            
            httpResult.success().message("驳回成功");
            
        } catch (Exception e) {
            logger.error("onRejectModified() - reject fail, exception = [{}]", e);
            httpResult.fail("500").message("驳回失败");
        }
        
        return httpResult;
        
    }
    
}
